﻿using System;
using System.Collections.Generic;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace GuildWars2PositionManaged2
{
    public class GuildWars2Position
    {
        private MemoryMappedFile MappedFile;
        private MemoryMappedViewStream ViewStream;
        private int LinkDataSize;

        public GuildWars2Position()
        {
            InitializeMemoryMap();
        }

        ~GuildWars2Position()
        {
            if (ViewStream != null)
            {
                ViewStream.Dispose();
            }
            if (MappedFile != null)
            {
                MappedFile.Dispose();
            }
        }

        private void InitializeMemoryMap()
        {
            var mmf = MemoryMappedFile.CreateOrOpen("MumbleLink", 1024 * 10);
            var view = mmf.CreateViewStream();

            MappedFile = mmf;
            ViewStream = view;
            LinkDataSize = Marshal.SizeOf(typeof(LinkData));
        }

        public LinkData Read()
        {
            LinkData data;

            byte[] byteData = new byte[LinkDataSize];
            ViewStream.Seek(0, System.IO.SeekOrigin.Begin);
            ViewStream.Read(byteData, 0, LinkDataSize);

            IntPtr intPtr = Marshal.AllocHGlobal(byteData.Length);
            Marshal.Copy(byteData, 0, intPtr, byteData.Length);
            data = (LinkData)Marshal.PtrToStructure(intPtr, typeof(LinkData));
            Marshal.FreeHGlobal(intPtr);

            return data;
        }
    }
}
